package com.rabbiter.association.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rabbiter.association.converter.StatusConverter;
import com.rabbiter.association.converter.UserTypeConverter;
import com.rabbiter.association.entity.Users;
import com.rabbiter.association.msg.PageData;
import com.rabbiter.association.msg.R;
import com.rabbiter.association.service.UsersService;
import com.rabbiter.association.utils.DateUtils;
import com.rabbiter.association.utils.IDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 系统请求响应控制器
 * 系统用户
 */
@Controller
@RequestMapping("/users")
@RequiredArgsConstructor
@Api(tags = "用户管理")
public class UsersController extends BaseController {

    protected static final Logger Log = LoggerFactory.getLogger(UsersController.class);

    private final UsersService usersService;

    private final PasswordEncoder passwordEncoder;

    @RequestMapping("")
    @ApiOperation(value = "分页查询用户")
    public String index() {

        return "pages/Users";
    }

    @GetMapping("/info")
    @ResponseBody
    @ApiOperation(value = "通过ID查询用户信息")
    public R getInfo(String id) {

        Log.info("查找指定系统用户，ID：{}", id);

        Users users = usersService.getOne(id);

        return R.successData(users);
    }

    @GetMapping("/page")
    @ResponseBody
    @ApiOperation(value = "分页查找系统用户")
    public R getPageInfos(Long pageIndex, Long pageSize,
                          Users users) {

        Log.info("分页查找系统用户，当前页码：{}，"
                        + "每页数据量：{}, 模糊查询，附加参数：{}", pageIndex,
                pageSize, users);

        PageData page = usersService.getPageInfo(pageIndex, pageSize, users);

        return R.successData(page);
    }

    @PostMapping("/add")
    @ResponseBody
    @ApiOperation(value = "添加系统用户")
    public R addInfo(@RequestBody Users users) {

        if (usersService.getUserByUserName(users.getUserName()) == null) {

            users.setId(IDUtils.makeIDByCurrent());
            users.setCreateTime(DateUtils.getNowDate());

            Log.info("添加系统用户，传入参数：{}", users);
            users.setPassWord(passwordEncoder.encode(users.getPassWord()));

            usersService.add(users);

            return R.success();
        } else {

            return R.warn("用户账号已存在，请重新输入");
        }
    }

    @PostMapping("/upd")
    @ResponseBody
    @ApiOperation(value = "修改系统用户")
    public R updInfo(Users users) {

        Log.info("修改系统用户，传入参数：{}", users);

        usersService.update(users);

        return R.success();
    }

    @PostMapping("/del")
    @ResponseBody
    @ApiOperation(value = "删除系统用户")
    public R delInfo(String id) {

        if (usersService.isRemove(id)) {

            Log.info("删除系统用户, ID:{}", id);

            Users users = usersService.getOne(id);

            usersService.delete(users);

            return R.success();
        } else {

            return R.warn("用户存在关联社团，无法移除");
        }
    }

    @GetMapping("/export")
    public void exportUsers(
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            HttpServletResponse response) throws IOException {

        // 1. 构建查询条件
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("user_name", userName);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like("phone", phone);
        }

        // 2. 查询数据
        List<Users> users = usersService.list(queryWrapper);
        List<Users> exportData = users.stream().map(Users -> {
            Users vo = new Users();
            BeanUtils.copyProperties(Users, vo);
            return vo;
        }).collect(Collectors.toList());

        // 3. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户信息表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 4. 导出Excel
        EasyExcel.write(response.getOutputStream(), Users.class)
                .registerConverter(new StatusConverter())
                .registerConverter(new UserTypeConverter())
                .sheet("用户数据")
                .doWrite(exportData);
    }

    @PostMapping("/import")
    public ResponseEntity<String> importUsers(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请上传文件");
        }

        // 1. 读取Excel数据
        List<Users> importData = EasyExcel.read(file.getInputStream())
                .head(Users.class)
                .sheet()
                .doReadSync();

        if (CollectionUtils.isEmpty(importData)) {
            return ResponseEntity.badRequest().body("Excel文件中没有数据");
        }

        // 2. 数据校验和转换
        List<Users> usersList = new ArrayList<>();
        StringBuilder errorMsg = new StringBuilder();
        int rowNum = 2; // Excel数据从第2行开始

        for (Users vo : importData) {
            try {
                // 验证必填字段
                if (StringUtils.isBlank(vo.getUserName())) {
                    throw new RuntimeException("用户账号不能为空");
                }
                if (StringUtils.isBlank(vo.getName())) {
                    throw new RuntimeException("姓名不能为空");
                }
                if (StringUtils.isBlank(vo.getPhone())) {
                    throw new RuntimeException("联系电话不能为空");
                }

                // 验证手机号格式
                if (!Pattern.matches("^1[3-9]\\d{9}$", vo.getPhone())) {
                    throw new RuntimeException("联系电话格式不正确");
                }

                // 转换数据
                Users user = new Users();
                BeanUtils.copyProperties(vo, user);

                // 设置默认值
                if (user.getStatus() == null) {
                    user.setStatus(1); // 默认状态为启用
                }
                if (user.getCreateTime() == null) {
                    user.setCreateTime(String.valueOf(new Date())); // 默认添加时间为当前时间
                }

                usersList.add(user);
            } catch (Exception e) {
                errorMsg.append("第").append(rowNum).append("行数据错误：").append(e.getMessage()).append("; ");
            }
            rowNum++;
        }

        // 如果有错误，返回错误信息
        if (errorMsg.length() > 0) {
            return ResponseEntity.badRequest().body(errorMsg.toString());
        }

        // 3. 批量保存数据
        try {
//            usersService.saveBatch(usersList);
            return ResponseEntity.ok("导入成功，共导入" + usersList.size() + "条数据");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("导入失败：" + e.getMessage());
        }
    }
}